package com.wanfajie.smsdistribute.common.adapter

import android.support.annotation.CallSuper
import android.support.v7.widget.RecyclerView
import android.view.View

abstract class SimpleRecyclerAdapter<E, VH: RecyclerViewHolder>() : RecyclerView.Adapter<VH>() {
    val items: List<E> get() = mItems
    protected abstract val mItems: MutableList<E>

    protected var mRecyclerView: RecyclerView? = null
    private var mClickListener : View.OnClickListener? = null
    private var mLongClickListener: View.OnLongClickListener? = null
    private var mItemClickListener: ((VH, E) -> Unit)? = null

    override fun getItemCount(): Int = mItems.size
    open fun getItem(index: Int) = mItems[index]

    override fun getItemId(position: Int): Long = position.toLong()

    @CallSuper
    override fun onBindViewHolder(p0: VH, p1: Int) {
        if (p0.view.tag == null) {
            p0.view.setOnClickListener {
                val vh = it.tag as VH
                val item: E = vh.tag as E

                mClickListener?.onClick(it)
                mItemClickListener?.invoke(vh, item)
            }
            p0.view.setOnLongClickListener(mLongClickListener)
            p0.view.tag = p0
        }

        p0.tag = getItem(p1)
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        mRecyclerView = recyclerView
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        mRecyclerView = null
    }

    open fun setOnClickListener(listener: View.OnClickListener?) {
        mClickListener = listener
    }

    open fun setOnClickListener(listener: (View) -> Unit) {
        mClickListener = View.OnClickListener(listener)
    }

    open fun setOnLongClickListener(listener: View.OnLongClickListener?) {
        mLongClickListener = listener
    }

    open fun setOnLongClickListener(listener: (View) -> Boolean) {
        mLongClickListener = View.OnLongClickListener(listener)
    }

    open fun setOnItemClickListener(listener: ((VH, E) -> Unit)) {
        mItemClickListener = listener
    }
}